<?php


namespace app\community\dbUtil;


class tableField
{
    protected array $field = [];

    /**
     * 设置表字段
     * @param string $fieldName 字段名
     * @param string $fieldType 字段类型
     * @param bool $notNull
     * @param int $fieldLength 字段长度
     * @param string|int|float $fieldDefault 字段默认值
     * @param string $fieldDescription 字段描述
     */
    public function setTableField(
        string $fieldName,
        string $fieldType,
        bool $notNull = true,
        int $fieldLength = 0,
        string|int|float $fieldDefault = '',
        string $fieldDescription = '暂无描述'
    ) {
        $this->field[$fieldName] = [
            'fieldName' => $fieldName,
            'fieldType' => $fieldType,
            'notNull' => $notNull,
            'fieldLength' => $fieldLength <= 0 ? '' : $fieldLength,
            'fieldDefault' => $fieldDefault,
            'fieldDescription' => $fieldDescription,
        ];
    }

    /**
     * 移除表单字段
     * @param string $fieldName 表字段名称
     * @return bool
     */
    public function removeTableField(string $fieldName): bool
    {
        if (!empty($this->field[$fieldName])) unset($this->field[$fieldName]);
        return true;
    }

    /**
     * 将 表字段生成Sql
     * @return string
     */
    public function buildTableFieldSql(): string
    {
        $sql = "";
        array_map(function ($field) use (&$sql){
            $sql .= "`{$field['fieldName']}`";

            $sql = $this->buildFieldSql($field, $sql);
        }, $this->field);
        return $sql;
    }

    /**
     * 获取第一个字段
     * @return array
     */
    public function firstColumn(): array
    {
        if (count($this->field) === 0) return [];
        $keys = array_keys($this->field);
        return $this->field[$keys[0]];
    }

    /**
     * 生成添加字段sql
     * @param string $tableName
     * @param string $type
     * @return array
     */
    public function buildAlterFieldSql(string $tableName, string $type = 'column'): array
    {
        $alterFieldSql = [];
        array_map(function ($field) use (&$alterFieldSql, $tableName, $type) {
            $sql = "alter table `{$tableName}` add {$type}";
            $alterFieldSql[] = $this->buildFieldSql($field, $sql);
        }, $this->field);
        return $alterFieldSql;
    }

    protected function buildFieldSql(array $field, string $sql): string
    {
        $sql .= $field['fieldLength']
            ? "{$field['fieldType']}({$field['fieldLength']})"
            : $field['fieldType'];

        if ($field['notNull']) {
            $sql .= " NOT NULL";
        }

        if ($field['fieldDefault']) {
            $sql .= " DEFAULT '{$field['fieldDefault']}'";
        }

        if ($field['fieldDescription']) {
            $sql .= " COMMENT '{$field['fieldDescription']}'";
        }
        return $sql;
    }
    

    /**
     * @return array
     */
    public function getField(): array
    {
        return $this->field;
    }

}